//门店列表数据
var storeManage = function() {

    var _init = function() {
        var table = $('#table_store');

        var tableUnit=table.dataTable({
            "processing": true,            
            serverSide: true,// 开启服务器模式
            "ajax": {
                url:storeList_url,
            },
            "autoWidth": false,
            "columns": [
                {"width": "15%","data": "name"},
                {
                    "width": "20%",
                    "data": "address",
                    "render" : function(data, type, row, meta) {
                        if(row.province.indexOf("市")<0){
                            return row.province+row.city+row.district+row.address;
                        }else{
                            return row.province+row.district+row.address;
                        }
                }
                },
                {"width": "11%","data": "phone"},
                {
                    "width": "15%",
                    "data": "openWeek",
                    "render": function(data, type, row, meta) {
                        return '周'+row.openWeek.replace(/周/g,'')+"</br>"+row.openTime+"至"+row.closeTime;
                    }
                },
                {
                    "width": "11%",
                    "data": "createDate",
                   "visible":false
                },
                {
                    "width": "10%",
                    "data": "is_close",
                    "render" : function(data, type, row, meta) {
                        if(row.is_close==1){
                            return '<button type="button" class="btn bg-green btn-xs is_close">营业中</button>';
                        }else{
                            return '<button type="button" class="btn bg-red btn-xs is_close">打烊中</button>';
                        }
                    }
                },
                {
                    "width": "15%",
                    "data": "null",
                    "defaultContent":
                        '<button type="button" class="btn btn-info btn-xs btn_edit_store">编辑</button>&nbsp;'+
                        '<button type="button" class="btn bg-purple btn-xs btn_product_store">货架</button>&nbsp;'+
                        '<button type="button" class="btn bg-orange btn-xs show_storecode">二维码</button>'
                }
            ],
            "language": {
                "lengthMenu": "每页显示 _MENU_ 条记录",
                "emptyTable": "暂无数据记录",
                "info": "显示 _START_ 至 _END_ 条数据，共 _TOTAL_ 条记录！",
                "zeroRecords": "没有搜索到匹配记录",
                "infoEmpty": "",
                "infoFiltered": "",
                "processing": "数据加载中,请稍后..."
            },
            "pageLength": 10,
            "ordering": false, // 禁止排序
            "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'table_b relative'<'col-md-5'i><'col-md-7'>lp>",
            "fnInitComplete": function() {},
            "fnDrawCallback": function(){
            }
           
        });

        // 新建门店
        $('#btn_new_tenant').click(function(event) {
            var oData_arr = table.DataTable().rows(0).data(); // 操作行对象
            var balance = parseInt($('#balance').val())
            var fee = parseInt($('#storeFee').val());
            if(oData_arr[0] !== undefined) {  //已有门店
                if(balance >= fee){
                    layer.alert('您已有门店，每开通一个门店收取'+fee+'元费用', {
                        btn: ['确定', '取消']
                        ,yes: function(index, layero){
                            window.location.href = storeAdd_url;
                        }
                        ,btn2: function(index, layero){
                            return;
                        }
                    });
                }else {
                    layer.open({
                        type: 1
                        ,title: "提示" //不显示标题栏   title : false/标题
                        ,closeBtn: true
                        ,area: '300px;'
                        ,shade: 0.5
                        ,id: 'LAY_layuipro' //设定一个id，防止重复弹出
                        ,resize: false
                        ,btn: ['去充值', '取消']
                        ,btnAlign: 'c'
                        ,moveType: 1 //拖拽模式，0或者1
                        ,content: '<div style="padding: 50px; line-height: 22px; background-color: #393D49; color: #fff; font-weight: 300;">您已有门店<br/>再开通一个门店收取'+fee+'元费用<br/>您的余额为：'+balance+'元<br/>商户余额不足请充值</div>'
                        ,success: function(layero){
                            var btn = layero.find('.layui-layer-btn');
                            btn.find('.layui-layer-btn0').click(function(){

                                window.location.href = "/admin/Tenant/index"
                            });
                        }
                    });
                }
            } else {  //第一个门店，需检测是否授权
                $.ajax({
                    url : checkWxstatus,
                    type : 'POST',
                    dataType : 'json',
                    contentType:"application/json; charset=utf-8",
                    async: false
                }).done(function(data) {
                    console.log(data);
                    if(data) {
                        window.location.href = storeAdd_url;
                    }else {
                        layer.alert('您还未授权小程序', {
                            btn: ['前去设置', '知道了']
                            ,yes: function(index, layero){
                                window.location.href = program_url
                            }
                            ,btn2: function(index, layero){
                            }
                        });
                    } 
                });
            }


            
        });

        //取消
        $('#return_user').click(function(event) {
        	window.history.back();
        });
        // 删除门店
        table.on('click', '.btn_del_store', function(event) {
            var oData_arr = table.DataTable().rows($(this).parents("tr")).data(); // 操作行对象
            var _id = oData_arr[0].id;
            bootbox.dialog({
				message : "确定要删除?",
				title : "提示",
				buttons : {
					cancel : {
						label : "取消",
						className : "btn dark btn-outline"
					},
					success : {
						label : "确定",
						className : "btn green",
						callback : function() {
							$.ajax({
            					url : storeDel_url,
            					type : 'delete',
            					dataType : 'json',
            					contentType:"application/json; charset=utf-8",
            					data : JSON.stringify({ id:_id}),
            					async: false
            				}).done(function(r) {
                                //console.log(r);
            					if (r.status === '1') { 
            						//table.DataTable().ajax.reload();
                                    table.DataTable().draw(false);
            					} else if (r.status === '2') {
                                    layer.msg(r.message);
            					}
            				});
						}
					}
				}
			});
            
        	//window.location.href="/p/user/mng/edit?id="+ encodeURIComponent(_id);
        });
       //时间日历
        $('#brithday').datepicker({
            language:"zh-CN", 
            todayBtn : "linked",  
            autoclose : true,  
            todayHighlight : true,  
            endDate : new Date()  
        })
        
        // 门店编辑
        table.on('click', '.btn_edit_store', function(event) {
            var oData_arr = table.DataTable().rows($(this).parents("tr")).data(); // 操作行对象
            var _id = oData_arr[0].id;
            window.location.href = storeEdit_url + "?id=" + encodeURIComponent(_id);
        });

        //门店货架
        table.on('click', '.btn_product_store', function(event) {
            var oData_arr = table.DataTable().rows($(this).parents("tr")).data(); // 操作行对象
            var _id = oData_arr[0].id;
            window.location.href = product_url + "?storeId=" + encodeURIComponent(_id);
        });
        table.on('click','.show_storecode',function (event) {
            var oData_arr = table.DataTable().rows($(this).parents("tr")).data(); // 操作行对象
            var _id = oData_arr[0].qrCode;

            openSelfDialog(_id);
            function openSelfDialog(id) {
                parent.layer.open({
                    title:'二维码',
                    type: 1,
                    skin: 'layui-layer-rim', //加上边框
                    area: ['450px', '600px'], //宽高
                    content: "<img src=" + "https://wechat-auth.1miaodao.cn/public/upload/" + id +">"
                });
            }


        });
        table.on('click','.is_close',function (event) {
            var oData_arr = table.DataTable().rows($(this).parents("tr")).data(); // 操作行对象
            var _is_close = oData_arr[0].is_close;
            var _id = oData_arr[0].id;
            if(_is_close == 1){
                layer.confirm('确定打烊吗？', {
                    btn: ['确定','取消'] //按钮
                }, function(){
                    $.ajax({
                        url : '/admin/Store/isclose',
                        type : 'POST',
                        dataType : 'json',
                        contentType:"application/json; charset=utf-8",
                        data : JSON.stringify({ id:_id,is_close:_is_close}),
                        async: false
                    }).done(function(r) {
                        //console.log(r);
                        if (r.status == 1) {
                            layer.msg('该店铺已经打烊',{time: 2000});
                            //table.DataTable().ajax.reload();
                            table.DataTable().draw(false);
                        } else {
                            layer.msg(r.message);
                        }
                    });

                }, function(){
                    layer.closeAll();
                });
            }else {
                layer.confirm('确定要开业吗？', {
                    btn: ['确定','取消'] //按钮
                }, function(){
                    $.ajax({
                        url : '/admin/Store/isclose',
                        type : 'POST',
                        dataType : 'json',
                        contentType:"application/json; charset=utf-8",
                        data : JSON.stringify({ id:_id,is_close:_is_close}),
                        async: false
                    }).done(function(r) {
                        //console.log(r);
                        if (r.status == 1) {

                            layer.msg('该店铺开始营业',{time: 2000});
                            //table.DataTable().ajax.reload();
                            table.DataTable().draw(false);
                        } else {
                            layer.msg(r.message);
                        }
                    });

                }, function(){
                    layer.closeAll();
                });
            }


        });
    }

    return {
        init: function() {
            _init();
        }
    };

}();


function ajaxRequestFee(){
    $.ajax({
        url : storeFee_url,
        type : 'post',
        dataType : 'json',
        contentType:"application/json; charset=utf-8",
        async: false
    }).done(function(data) {
        layer.msg(data.message);
        if (data.status == '1') {  //TODO
        } else if (data.status == '2') {
        }
    });
}

$(function() {
    storeManage.init();
});